package com.nowcoder.community.controller.interceptor;

import com.nowcoder.community.entity.LoginTicket;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.MessageService;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.CommunityUtils;
import com.nowcoder.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * 读取ticket获取登录用户对象
 */
@Component
public class LoginTicketInterceptor implements HandlerInterceptor {
    @Autowired
    UserService userService;

    @Autowired
    MessageService messageService;

    @Autowired
    HostHolder hostHolder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        String ticket = CommunityUtils.getCookieValue(request, "ticket");
        User user;
        if (ticket == null || ticket.isEmpty()) {
            return true;
        }
        LoginTicket loginTicket = userService.findLoginTicket(ticket);
        if (
                loginTicket != null && loginTicket.getStatus() == 0 &&
                loginTicket.getExpired().after(new Date()) &&
                (user = userService.findUserById(loginTicket.getUserId())) != null
        ) {
            user.setUnreadMessageCount(messageService.getUserMessageUnread(user.getId()));
            hostHolder.setUser(user);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        User user = hostHolder.getUser();
        if (user != null) {
            user.setUnreadMessageCount(messageService.getUserMessageUnread(user.getId()));
        }
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex){
        hostHolder.clean();
    }
}
